package com.wyh.contorller;

import com.wyh.entity.Activity;
import com.wyh.entity.RestBean;
import com.wyh.mapper.ActivityMapper;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Validated
@RestController
@RequestMapping("/api/activity")
public class ActivityController {

    @Resource
    ActivityMapper activityMapper;

    //findByIdOrName
    @RequestMapping("/find")
    public RestBean<String> selectActivityByIdOrName(Activity activity) {
        String c = activityMapper.selectActivityByIdOrName(activity);
        if (c != null) {
            try {
                return RestBean.success(String.valueOf(activity));
            } catch (Exception e) {
                return RestBean.failure(400);
            }
        }
        return RestBean.failure(400);
    }

    //getAll
    @GetMapping("/getAll")
    public RestBean<List<Activity>> getAllActivity() {
        List<Activity> activities = activityMapper.getAllActivity();
        if (activities != null) {
            return RestBean.success(activities);
        }
        return RestBean.failure(400);
    }

    //add
    @PostMapping("/add")
    public RestBean<String> add(Activity activity) {
        try {
            activityMapper.selectActivityByIdOrName(activity);
            activity.setId(activity.getId());
            activity.setName(activity.getName());
            activity.setType(activity.getType());
            activity.setTime(activity.getTime());
            activity.setAddress(activity.getAddress());
            activity.setOrganizer_user_id_fk(activity.getOrganizer_user_id_fk());
            activity.setRemark(activity.getRemark());
            activityMapper.addActivity(activity);
            return RestBean.success("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RestBean.failure(400, "已经申请过该活动，或者名称和id重复" + e.getMessage());
        }
    }

    //delete
    @DeleteMapping("/delete")
    public RestBean<String> delete(Activity activity) {
        try {
            activityMapper.deleteActivity(activity.getId());
            return RestBean.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return RestBean.failure(400, "删除失败" + e.getMessage());
        }
    }


    @PutMapping("/update")
    public RestBean<String> updateRemark(@RequestBody Activity activity) {
        try {
            Activity a = activityMapper.findActivityById(activity.getId());
            if (a != null) {
                activityMapper.updateActivity(activity);
                return RestBean.success("修改成功");
            } else
                return RestBean.failure(400, "修改失败，活动不存在");
        } catch (Exception e) {
            e.printStackTrace();
            return RestBean.failure(400, "修改失败" + e.getMessage());
        }
    }
}
